package com.kologe.transandroid.server;



//实现tcplisten的功能，监听tcp请求，并进行交互

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NTcpListener implements  Runnable{
    private  String ip;
    private  int port;

    public NTcpListener(String ip,int port){
        this.ip = ip;
        this.port = port;
    }
    public NTcpListener(int port){
        this.port = port;
    }

    public  void run(){

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class).childHandler(new DataDealChannel());
            ChannelFuture f = b.bind(new InetSocketAddress(port)).sync();


            InetSocketAddress localAddress = (InetSocketAddress) f.channel().localAddress();
            String serverIP = localAddress.getAddress().getHostAddress(); // 服务端 IP [[3, 5, 18]]
            int serverPort = localAddress.getPort(); // 服务端端口 [[3, 5]]
            System.out.println("Server is listening on IP: " + serverIP + ", port: " + serverPort);
        }catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}


